<!-- src/views/LoginView.vue -->
<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <span>用户登录</span>
        </div>
      </template>

      <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          label-width="80px"
          @submit.prevent="handleLogin"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              clearable
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              show-password
          />
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="loginForm.remember" label="记住密码" />
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              @click="handleLogin"
              :loading="loading"
              style="width: 100%"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>

        <el-form-item>
          <el-button
              type="text"
              @click="goToRegister"
              style="width: 100%"
          >
            没有账号？立即注册
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import type {FormInstance, FormRules} from 'element-plus'
import {loginApi} from '@/api/request'
import {ElMessage} from 'element-plus'

// 表单数据
const loginForm = reactive({
  username: '',
  password: '',
  remember: false
})

// 表单验证规则
const loginRules = reactive<FormRules>({
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 20, message: '密码长度为6-20个字符', trigger: 'blur'}
  ]
})

// 表单引用
const loginFormRef = ref<FormInstance>()

// 状态
const loading = ref(false)
const router = useRouter()

// 组件挂载时检查是否保存了用户名
onMounted(() => {
  const savedUsername = localStorage.getItem('savedUsername')
  const rememberPassword = localStorage.getItem('rememberPassword') === 'true'

  if (savedUsername && rememberPassword) {
    loginForm.username = savedUsername
    loginForm.remember = true
  }
})

// 登录处理函数
const handleLogin = async () => {
  if (!loginFormRef.value) return

  // 使用 try/catch 处理表单验证
  try {
    // @ts-ignore 忽略类型检查错误
    await loginFormRef.value.validate()
    await performLogin()
  } catch (error) {
    console.log('表单验证失败')
  }
}

// 执行登录
const performLogin = async () => {
  loading.value = true

  try {
    // 处理记住密码功能
    if (loginForm.remember) {
      localStorage.setItem('savedUsername', loginForm.username)
      localStorage.setItem('rememberPassword', 'true')
    } else {
      // 如果用户取消了记住密码，清除之前保存的用户名
      localStorage.removeItem('savedUsername')
      localStorage.removeItem('rememberPassword')
    }

    console.log('发送登录请求:', {
      username: loginForm.username,
      password: loginForm.password,
      remember: loginForm.remember
    })

    // 调用登录接口（发送remember字段到后端）
    const response = await loginApi({
      username: loginForm.username,
      password: loginForm.password,
      remember: loginForm.remember  // 发送给后端
    })

    console.log('收到登录响应:', response)

    // 检查响应是否成功 (简化后的写法)
    if (response.success) {
      // 确保响应数据存在
      if (response.data && response.data.accessToken && response.data.refreshToken && response.data.user) {
        // 保存用户信息和token到 localStorage
        localStorage.setItem('accessToken', response.data.accessToken)
        localStorage.setItem('refreshToken', response.data.refreshToken)
        localStorage.setItem('userInfo', JSON.stringify({
          id: response.data.user.id,
          username: response.data.user.username,
          role: response.data.user.role,
          expiration: Date.now() + 15 * 60 * 1000 // 15分钟后过期(与JWT设置一致)
        }))

        // 跳转到首页
        router.push('/')

        ElMessage.success('登录成功')
      } else {
        ElMessage.error('登录响应数据不完整')
      }
    } else {
      // 只显示后端返回的错误消息，不显示通用错误
      const errorMessage = response?.message || '登录失败'
      ElMessage.error(errorMessage)
      console.error('登录失败:', errorMessage)
    }
  } catch (error: any) {
    console.error('登录异常:', error)
    // 只显示后端返回的错误消息，不显示通用错误
    if (error.response && error.response.data) {
      const errorMessage = error.response.data.message || '用户名或密码错误'
      ElMessage.error(errorMessage)
      console.error('登录失败响应:', error.response.data)
    } else {
      ElMessage.error('登录失败，请检查网络或稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f2f5;
  margin: 0;
  padding: 20px;
  box-sizing: border-box;
}

.login-card {
  width: 100%;
  max-width: 400px;
  max-height: calc(100vh - 40px);
  overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-container {
    padding: 10px;
  }

  .login-card {
    max-height: calc(100vh - 20px);
  }
}

@media (max-height: 600px) {
  .login-container {
    align-items: flex-start;
    padding-top: 10px;
  }

  .login-card {
    max-height: calc(100vh - 20px);
  }
}
</style>
